/*
 * @Description: 
 * @Author: fhw
 * @Date: 2022-11-18 16:39:53
 */
import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { clone, equals } from 'ramda';
import { GroupChatRecord } from 'src/chat-record/entities/group-chat-record.entity';
import { UserChatRecord } from 'src/chat-record/entities/user-chat-record.entity';
import { ChatUserService } from 'src/chat_user/chat_user.service';
import { ChatUserGroup } from 'src/chat_user_group/entities/chat_user_group.entity';
import { GroupChatService } from 'src/group-chat/group-chat.service';
import { socketError, socketSuccess, SocketType } from 'src/utlis';
import { Repository } from 'typeorm';
import { GroupChatMessageDto } from './dto/socket-room.dto';

@Injectable()
export class SocketRoomService {
    constructor(
        @InjectRepository(GroupChatRecord)
        private groupChatRecordRepository: Repository<GroupChatRecord>,
        @InjectRepository(ChatUserGroup)
        private ChatUserGroupRepository: Repository<ChatUserGroup>,
        @Inject(forwardRef(() => ChatUserService)) private readonly chatUserService: ChatUserService,
        @Inject(forwardRef(() => GroupChatService)) private readonly GroupChatService: GroupChatService,
    ) { }
    async groupChatMessage(params: GroupChatMessageDto): Promise<GroupChatRecord | SocketType> {
        try {
            if (equals(typeof params, 'string')) {
                params = JSON.parse(params as any)
            }
            const { userId, content, type, group_id } = params
            const user = await this.chatUserService.getUserInfo({ id: userId })
            const groupChat = await this.GroupChatService.getGroupChatInfo({ group_id })
            const groupChatRecord: GroupChatRecord = new GroupChatRecord()
            groupChatRecord.userId = userId
            groupChatRecord.user = user
            groupChatRecord.content = content
            groupChatRecord.type = type
            groupChatRecord.groupChat = groupChat
            groupChatRecord.group_id = group_id
            const result = await this.groupChatRecordRepository.manager.save(groupChatRecord)
            return result
        } catch (error) {
            return socketError(error.message) as SocketType
        }
    }
    /** 获取群聊未读消息 */
    async getGroupUnreadRecord(userId: number) {
        const groupUnreadRecord = await this.ChatUserGroupRepository.find({
            where: {
                userId
            }
        })
        const data = {}
        groupUnreadRecord.filter(item => equals(item?.is_join, 1)).forEach(item => {
            data[item.group_id] = {
                count: item.unread_num, latestNews: clone(item.groupChat.latestNews)
            };
        })
        return data
    }
    /** 更新用户未读消息 */
    async setGroupChatRead(group_id: string, userId: string) {
        try {
            const { affected } = await this.ChatUserGroupRepository
                .createQueryBuilder()
                .update(ChatUserGroup)
                .set({
                    unread_num: 0
                })
                .where({ group_id, userId })
                .execute()
            if (affected) {
                return socketSuccess('更新用户未读消息成功')
            }
            return socketError('更新用户未读消息失败')
        } catch (error) {
            return socketError(error.message)
        }
    }
    /** 更新群用户未读记录 */
    async updateChatUserGroup(group_id, userId) {
        try {
            const chatUserGroup = await this.ChatUserGroupRepository.find({
                where: { group_id }
            })
            const promiseAll = chatUserGroup.filter(item => !equals(item.userId, userId)).map(item => {
                return this.ChatUserGroupRepository
                    .createQueryBuilder()
                    .update(ChatUserGroup)
                    .set({
                        unread_num: (item.unread_num ?? 0) + 1
                    })
                    .where({ id: item.id })
                    .execute()
            })
           return Promise.all(promiseAll)
        } catch (error) {

        }
    }
    /** 获取群聊用户 */
    async getChatUserGroup(group_id: string) {
        try {
            return await this.ChatUserGroupRepository.find({ where: { group_id } })
        } catch (error) {

        }
    }
}
